//
//  RMMChosseDateViewController.m
//  Romomo
//
//  Created by puman on 16/10/12.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMChosseDateViewController.h"
#import "RMMDateUpView.h"
#import "RMMChooseSkillViewController.h"
#import "RMMChooseFuWuViewController.h"
#import "RMMUpOrderViewController.h"

@interface RMMChosseDateViewController ()

@end

@implementation RMMChosseDateViewController
{
    NSInteger _buttonTag;
    NSInteger _dateButTag;
    RMMDateUpView *_dateUpView;
    RMMNotNetWorkView *_networkView;
    NSMutableDictionary *_statusDic;
    NSMutableDictionary *_dataDic;
    UIButton *_bottomBut;
    NSArray *_titleArray;
    NSMutableArray *_dateTimeArray;
    
    UIScrollView *_scrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.title = @"选择服务开始时间";
    _dateButTag = 10;;
    [self addViews];
    [self addLeftItem];
    [self getRequestData];
    // Do any additional setup after loading the view.
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;
   // item.tintColor = COLORFROMCODE(0x9B9B9B1, 1);
    
}
- (void)addViews{
    _statusDic = [NSMutableDictionary dictionary];
    _dateTimeArray = [NSMutableArray array];
    _dataDic = [NSMutableDictionary dictionary];
    [self addDateView];
}
- (void)getRequestData{
    NSDictionary *dic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"];
      id adress_id = [dic objectForKey:@"ID"];
    NSString * emp_id = [RMMFileManager retrunObjWith:[[RMMFileManager shareHandle].bookingDic objectForKey:@"技师"][@"EMP_ID"]];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"regin_id"] = [RMMFileManager shareHandle].region_id;
    parDic[@"service_type"] = _isHome;
    parDic[@"res_type"] = @"1";
    if ([_isHome isEqualToString:@"1"]) {
        parDic[@"address_id"] = adress_id;
        parDic[@"store_id"] = @"-10";
    } else {
        parDic[@"address_id"] = @"-1";
        parDic[@"store_id"] = adress_id;
    }
    parDic[@"emp_id"] = emp_id.length == 0 ? @"" : emp_id;
    if (_order_id.length) {
        parDic[@"order_id"] = _order_id;
    }
    if (_dateButTag == 10) {
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *nowTime = [dateFormatter stringFromDate:date];
        parDic[@"query_time"] = nowTime;
    } else {
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:24 * 60 * 60 * (_dateButTag - 10)];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *nowTime = [dateFormatter stringFromDate:date];
        parDic[@"query_time"] = [NSString stringWithFormat:@"%@ 00:00:00", nowTime];
    }
    parDic[@"time_len"] = [RMMFileManager shareHandle].totalTimeLength;
    NSString *url = GetTimeOrSkillUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:POST finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            for (NSDictionary *dic in array) {
                if ([dic[@"Is_Avaliable"] isEqualToNumber:@1]) {
                    NSMutableArray *array = _dataDic[@"可选"];
                    if (array == nil) {
                        array = [NSMutableArray array];
                        [_dataDic setObject:array forKey:@"可选"];
                    }
                    NSString *time = dic[@"Res_Date"];
                    NSString *dateTime = [time substringWithRange:NSMakeRange(time.length - 8, 5)];
                    if ([[dateTime substringToIndex:1] isEqualToString:@" "]) {
                        dateTime = [NSString stringWithFormat:@"0%@",[dateTime substringFromIndex:1]];
                    }
                    [array addObject:dateTime];
                }
            }
            [self showTimeWithDic:_dataDic];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }

    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 展示可用/不可用时间
- (void)showTimeWithDic:(NSMutableDictionary *)dic{
    NSMutableArray *array = _dataDic[@"可选"];
    for (int i = 0; i < 25; i++) {
        UIButton *buttons = [self.view viewWithTag:50 + i];
        NSString *title = [buttons titleForState:(UIControlStateNormal)];
        if ([array containsObject:title]) {
            [buttons setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
            buttons.backgroundColor = kWhiteColor;
            buttons.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
            if (_dateButTag == 10) {
                NSDate *date = nil;
                NSDateFormatter* formatter = [NSDateFormatter new];
                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                if ([_isHome isEqualToString:@"1"]) {
                    date = [[NSDate alloc] initWithTimeIntervalSinceNow:30 * 60];
                } else {
                    date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
                }
                NSString *time = [formatter stringFromDate:date];
                NSString *timeString = [time substringWithRange:NSMakeRange(11, 5)];
                if ([timeString compare: title] == NSOrderedDescending) {
                    buttons.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
                    [buttons setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
                    buttons.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
                }
            }
        } else {
            buttons.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
            [buttons setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
            buttons.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
        }
    }

}
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addDateView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 60)];
    _scrollView.backgroundColor = kWhiteColor;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < 14; i++) {
        
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:i * 24 * 60 * 60];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateTime = [formatter stringFromDate:date];

        UILabel *weekLabel = [[UILabel alloc] initWithFrame:CGRectMake(15 + 70 * i, 0, 60, 30)];
        weekLabel.textColor = COLORFROMCODE(0xBFBFBF, 1);
        weekLabel.font = kFont(13);
        weekLabel.tag = 200 + i;
        weekLabel.text = [self getNowWeekdayWith:date];
        weekLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:weekLabel];
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(15 + 70 * i,0, 60, 58);
        [button setTitle:[self getDateTimeWithString:dateTime] forState:(UIControlStateNormal)];
        [button setTitleColor:COLORFROMCODE(0xBFBFBF, 1) forState:(UIControlStateNormal)];
        button.titleLabel.numberOfLines = 0;
        button.titleEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
        button.tag = 10 + i;
        NSMutableArray *timeArray = [NSMutableArray array];
        for (int j = 0; j < 25; j++) {
            [timeArray addObject:@"0"];
        }
        BUTTON_S(button, dateClick:);
        button.titleLabel.font = kFont(13);
        [_scrollView addSubview:button];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(button.left, button.bottom, button.width, 2)];
        label.backgroundColor = kBasicColor;
        label.tag = 30 + i;
        label.hidden = YES;
        [_scrollView addSubview:label];
        
        if (i == 0) {
            [button setTitleColor:kBasicColor forState:(UIControlStateNormal)];
            weekLabel.textColor = kBasicColor;
            label.hidden = NO;
        }

    }
    
    [_scrollView setContentSize:CGSizeMake(20 + 70 * 14, 60)];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, _scrollView.bottom, kScreenWideth, 54)];
    view.backgroundColor = RGBA(245, 246, 247, 1);
    [self.view addSubview:view];
    NSArray *arrayS = @[@"可选",@"已选",@"已满"];
    for (int i = 0; i < 3; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWideth / 2 - 90 + 60 * i, 20, 20, 14)];
        label.layer.masksToBounds = YES;
        label.layer.masksToBounds = YES;
        label.layer.cornerRadius = 7;
        [view addSubview:label];
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(label.right, label.top, 40, 14)];
        nameLabel.text = arrayS[i];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.textColor = COLORFROMCODE(0xAEAEAE, 1);
        nameLabel.font = kFont(14);
        [view addSubview:nameLabel];
        if (i == 0) {
            label.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
            label.layer.borderWidth = 1;
        } else if (i == 1) {
            label.backgroundColor = kBasicColor;
        } else {
            label.backgroundColor = COLORFROMCODE(0xEEEEEE, 1);
        }
    }
    CGFloat width = (kScreenWideth - 30 - 36) / 5;
    CGFloat height = 32 * (width / 62);
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, view.bottom, kScreenWideth, 36 + height * 5 + 40)];
    buttonView.backgroundColor = kWhiteColor;
    [self.view addSubview:buttonView];
    _titleArray = @[@"10:00",@"10:30",@"11:00",@"11:30",@"12:00",@"12:30",@"13:00",@"13:30",@"14:00",@"14:30",@"15:00",@"15:30",@"16:00",@"16:30",@"17:00",@"17:30",@"18:00",@"18:30",@"19:00",@"19:30",@"20:00",@"20:30",@"21:00",@"21:30",@"22:00"];
    for (int i = 0; i < 25; i++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake((i % 5) * (width + 9) + 15,  18 + (height + kRow) * (i / 5) , width, height);
        button.layer.cornerRadius = height / 2;
      //  button.layer.masksToBounds = YES;
        button.layer.borderWidth = 1;
        button.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
        button.titleLabel.font = kFont(14);
        [button setTitle:_titleArray[i] forState:(UIControlStateNormal)];
        [button setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
        button.tag = 50 + i;
        BUTTON_S(button, timeButtonClick:);
        [buttonView addSubview:button];
        if (i > 20) {
            if ([_isHome isEqualToString:@"1"]) {
                button.hidden = NO;
            } else {
                button.hidden = YES;
            }
        }
    }
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    bottomView.backgroundColor = kWhiteColor;
    [self.view addSubview:bottomView];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 0.5)];
    lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
    [bottomView addSubview:lineLabel];
    
    _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _bottomBut.frame = CGRectMake(kScreenWideth / 2 - kHalf * 2, 6.5, 4 * kHalf, 36);
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _bottomBut.titleLabel.font = kBFont(14);
    _bottomBut.layer.masksToBounds = YES;
    _bottomBut.layer.cornerRadius = 18;
    [_bottomBut setTitle:@"下一步" forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = NO;
    BUTTON_S(_bottomBut, nextButClick);
    [bottomView addSubview:_bottomBut];
    
//    _dateUpView = [[RMMDateUpView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
//    _dateUpView.hidden = YES;
//    [self.view addSubview:_dateUpView];
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
}
- (void)networkBut{
    [self getRequestData];
}
// 下一步
- (void)nextButClick{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        RMMUpOrderViewController *VC = [[RMMUpOrderViewController alloc] init];
        [[RMMFileManager shareHandle].bookingDic setValue:[NSString stringWithFormat:@"%@ %@",_dateTimeArray[_dateButTag - 10],_titleArray[_buttonTag - 50]] forKey:@"时间"];
        VC.isHome = _isHome;
        VC.dataArray = _dataArray;
        VC.youHuiDic = _youHuiDic;
        VC.isHome = _isHome;
        VC.dataDic = _order_id_dic;
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        if ([_type isEqualToString:@"1"]) {
            [[RMMFileManager shareHandle].bookingDic setValue:[NSString stringWithFormat:@"%@ %@",_dateTimeArray[_dateButTag - 10],_titleArray[_buttonTag - 50]] forKey:@"时间"];
            NSArray *VCArray = self.navigationController.viewControllers;
            for (UIViewController *VC in VCArray) {
                if ([VC isKindOfClass:[RMMUpOrderViewController class]]) {
                    [self.navigationController popToViewController:VC animated:YES];
                }
            }
        } else {
            RMMChooseSkillViewController *VC = [[RMMChooseSkillViewController alloc] init];
            VC.type = _type;
            VC.isHome = _isHome;
            [[RMMFileManager shareHandle].bookingDic setValue:[NSString stringWithFormat:@"%@ %@",_dateTimeArray[_dateButTag - 10],_titleArray[_buttonTag - 50]] forKey:@"时间"];
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
}
- (void)timeButtonClick:(UIButton *)button{
    _buttonTag = button.tag;
    UIColor *color = [button backgroundColor];
    if ([color isEqual:COLORFROMCODE(0xEEEEEE, 1)]) {
//        _dateUpView.hidden = NO;
//        [UIView animateWithDuration:kInterval animations:^{
//            _dateUpView.backView.frame = CGRectMake(0, kScreenHeight - 260 - 64, kScreenWideth, 260);
//            _dateUpView.view.alpha = 1.0;
//        } completion:^(BOOL finished) {
//            
//        }];
    } else {
        NSString *key = [NSString stringWithFormat:@"%ld",_buttonTag];
        NSString *stat = _statusDic[key];
        if ([stat isEqualToString:@"1"]) {
            [_statusDic setObject:@"0" forKey:key];
            [button setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
            button.backgroundColor = kWhiteColor;
            button.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
        } else {
            [_statusDic setObject:@"1" forKey:key];
            button.layer.borderColor = kBasicColor.CGColor;
            [button setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
            button.backgroundColor = kBasicColor;
        }
        for (int i = 0; i < [_statusDic allKeys].count; i++) {
            NSArray *keyArray = [_statusDic allKeys];
            NSString *keys = keyArray[i];
            if ([keys integerValue] != _buttonTag) {
                UIButton *buttons = [self.view viewWithTag:[keys integerValue]];
                [buttons setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
                buttons.backgroundColor = kWhiteColor;
                buttons.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
                [_statusDic setObject:@"0" forKey:keys];
            }
        }
        // 注意:这个地方用forin遍历会crash原因是,forin没有遍历完成之前,系统是不允许修改遍历对象。当遍历到最后一个的时候就可以修改(因为已经遍历完成),改变方法用for(i,i <,i++)来遍历就不会crash了
//        for (NSString *keys in _statusDic) {
//            if ([keys integerValue] != _buttonTag) {
//                UIButton *buttons = [self.view viewWithTag:[keys integerValue]];
//                [buttons setTitleColor:COLORFROMCODE(0xB5B5B5, 1) forState:(UIControlStateNormal)];
//                buttons.backgroundColor = kWhiteColor;
//                buttons.layer.borderColor = COLORFROMCODE(0xD7D7D7, 1).CGColor;
//                [_statusDic setObject:@"0" forKey:keys];
//            }
//        }
        for (NSString *keys in _statusDic) {
            NSString *value = _statusDic[keys];
            if ([value isEqualToString:@"1"]) {
                _bottomBut.backgroundColor = kBasicColor;
                [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
                _bottomBut.userInteractionEnabled = YES;
                return;
            } else {
                _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
                [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
                _bottomBut.userInteractionEnabled = NO;
            }
        }
    }
}
- (void)dateClick:(UIButton *)button{
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = NO;
    _dateButTag = button.tag;
    if (button.right <= kScreenWideth - 30) {
        if (_scrollView.contentOffset.x != 0) {
            [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
    } else if (button.right > kScreenWideth -  30 && button.right < 20 + 70 * 14 - kScreenWideth + 20) {
        CGFloat centrtX = kScreenWideth / 2;
        CGFloat buttonCenterX = button.left + button.width / 2;
        CGFloat x = buttonCenterX - centrtX;
        [_scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
    } else {
        if (_scrollView.contentOffset.x != 20 + 70 * 14 - kScreenWideth + 20) {
            [_scrollView setContentOffset:CGPointMake(20 + 70 * 14 - kScreenWideth, 0) animated:YES];
        }
    }
    for (int i = 0; i < 14; i++) {
        UILabel *weekLabel = [self.view viewWithTag:200 + i];
        weekLabel.textColor = COLORFROMCODE(0xBFBFBF, 1);
        UILabel *label = [self.view viewWithTag:30 + i];
        label.hidden = YES;
        UIButton *buttons = [self.view viewWithTag:10 + i];
        [buttons setTitleColor:COLORFROMCODE(0xBFBFBF, 1) forState:(UIControlStateNormal)];
        if (buttons.tag == _dateButTag) {
            [buttons setTitleColor:kBasicColor forState:(UIControlStateNormal)];
            UILabel *labels = [self.view viewWithTag:_dateButTag + 20];
            labels.hidden = NO;
        }
        if (weekLabel.tag == _dateButTag + 190) {
            weekLabel.textColor = kBasicColor;
        }
    }
    [_dataDic removeAllObjects];
    [_statusDic removeAllObjects];
    [self getRequestData];
}
//
- (NSString *)getDateTimeWithString:(NSString *)string{
    [_dateTimeArray addObject:string];
    NSString *mouth = [string substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [string substringFromIndex:8];
    NSInteger mouths = [mouth integerValue];
    NSInteger days = [day integerValue];
    return [NSString stringWithFormat:@"%ld月%ld日",mouths,days];
}
- (NSString *)getNowWeekdayWith:(NSDate *)date{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:date];
    NSInteger week = [theComponents weekday];
    NSString *weekDay = nil;
    switch (week) {
        case 1:
            weekDay = @"星期日";
            break;
        case 2:
            weekDay = @"星期一";

            break;
        case 3:
            weekDay = @"星期二";

            break;
        case 4:
            weekDay = @"星期三";

            break;
        case 5:
            weekDay = @"星期四";

            break;
        case 6:
            weekDay = @"星期五";

            break;
        case 7:
            weekDay = @"星期六";

            break;
            
        default:
            break;
    }
    return weekDay;
}
- (void)bottomBut{
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
